package com.platform.modules.order;

import com.platform.common.exception.BusinessException;
import com.platform.modules.mall.entity.MallGoodsEntity;
import com.platform.modules.mall.entity.MallOrderEntity;
import com.platform.modules.mall.entity.MallUserEntity;
import com.platform.modules.mall.service.MallGoodsService;
import com.platform.modules.mall.service.MallOrderGoodsService;
import com.platform.modules.mall.service.MallOrderService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Component
public class OrderBootstrap {

    @Resource
    MallOrderService orderService;
    @Resource
    MallOrderGoodsService orderGoodsService;

    @Resource
    MallGoodsService mallGoodsService;

    public MallOrderEntity createOrder(IOrderBuildSelect buildSelect, ParamsEntity params, MallUserEntity loginUser) {
        return this.createOrder(buildSelect.selectOrderBuild(params, loginUser));
    }

    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_UNCOMMITTED)
    public MallOrderEntity createOrder(AbsOrderBuild orderBuild) {
        if (orderBuild == null) {
            throw new BusinessException("orderBuild 不能为空！");
        }
        // 参数校验
//        orderBuild.paramsVerify();
        synchronized (orderBuild.user.getId().intern()) {
            // 限购判断
            orderBuild.limited();
            // 减库存
            orderBuild.minusGoodsNumber();
            try {
                // 构建订单

                MallGoodsEntity goods = mallGoodsService.getById(orderBuild.params.getGoodsId());
                orderBuild.orderInfo(goods);
                // 保存订单
                orderService.save(orderBuild.getOrderEntity());
                if (null == orderBuild.getOrderEntity().getId()) {
                    throw new BusinessException("订单提交失败！");
                }
                // 构建订单详情
                orderBuild.orderGoods();
                // 保存订单详情
                orderGoodsService.saveBatch(orderBuild.getOrderEntity().getOrderGoodsEntityList());
                // 订单保存后执行
                orderBuild.saveAfter();
            } catch (Exception e) {
                e.printStackTrace();
                // 异常执行
                orderBuild.exceptionHandle();
            }
        }
        return orderBuild.getOrderEntity();
    }

}
